/** 
 * @Title:  FragmentController.java 
 * @author:  Abtswiath丶lxy
 * @data:  2016年6月8日 上午10:56:16 <创建时间>
 * 
 * @history：<以下是历史记录>
 *
 * @modifier: <修改人>
 * @modify date: 2016年6月8日 上午10:56:16 <修改时间>
 * @log: <修改内容>
 *
 * @modifier: <修改人>
 * @modify date: 2016年6月8日 上午10:56:16 <修改时间>
 * @log: <修改内容>
 */
package com.sunmi.usercenter.controller;

import java.util.List;

import com.sunmi.usercenter.Constant;
import com.sunmi.usercenter.R;
import com.sunmi.usercenter.bean.FmInfo;
import com.sunmi.usercenter.ui.activity.fragment.SuperFragment;
import com.sunmi.usercenter.utils.LogUtil;

import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;

/**
 * TODO<请描述这个类是干什么的>
 * 
 * @author Abtswiath丶lxy
 * @versionCode 1 <每次修改提交前+1>
 */
public class FragmentController extends SuperController implements IFragmentController {

	private static final String TAG = "FragmentController";
	private FragmentManager fm;

	private static FragmentController mFragmentController;

	private FragmentController(Context mContext, FragmentManager fm) {
		super(mContext);
		this.fm = fm;
	}

	public static FragmentController getInstance(Context mContext, FragmentManager fm) {
		// if (mChannelController == null) {
		mFragmentController = new FragmentController(mContext, fm);
		// }
		return mFragmentController;
	}
	

	@Override
	public void openFM(FmInfo fmInfo) {
		Constant.CLASS_FRAGMENT = "";
		Class<SuperFragment> nowClass = fmInfo.getNowClass();
		String fmName = nowClass.getName();
		List<Fragment> list = fm.getFragments();
//		if(list!=null&&list.size()>0){
//			for(int i=0;i<list.size();i++){
//				Fragment fragment = list.get(i);
//				LogUtil.d(TAG, "position:"+i+" name:"+fragment);
//			}
//		}

		SuperFragment nowFm = (SuperFragment) fm.findFragmentByTag("" + fmName);
		FragmentTransaction ft = fm.beginTransaction();
		if (nowFm == null) {
			try {
				// 反射得到Fragment实例
				nowFm = nowClass.newInstance();
			} catch (InstantiationException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		}
		// 传递参数
		nowFm.setInfo(fmInfo.getInfo());
		ft.replace(R.id.channel_layout, nowFm, fmName);
		ft.addToBackStack(null);
		// 提交事务
		ft.commitAllowingStateLoss();
	}

	@Override
	public void closeFM() {
		List<Fragment> list = fm.getFragments();
		FragmentTransaction ft = fm.beginTransaction();
		Fragment fragment = list.get(list.size() - 1);
		LogUtil.d(TAG, "remove fm:"+ fragment);
		ft.remove(fragment);
		// 提交事务
		ft.commitAllowingStateLoss();
	}

}
